package com.yachtar.property;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.yachtar.property.db.DBService;
import com.yachtar.property.db.TUseHouse;
import com.yachtar.property.idcard.IDCard;
import com.yachtar.property.idcard.IdCardManager;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class IdCardReaderActivity extends Activity {
	private TextView tv;
	private IdCardManager mManager;
	private int point;
	private Handler mHandler = new Handler();
	private DBService mDBService;
	private AlertDialog dialog;
	private static final  String rfidpower_filepath = "/proc/devicepower/rfidpower";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.idcardreader);
		//WritePowerstate(rfidpower_filepath,'1');
		tv = (TextView) findViewById(R.id.idcardreader_tv);
		mDBService = DBService.getInstance();

	}
	static public int  WritePowerstate(String file_path, char state)
	{
		File file = new File(file_path);
		if (!file.exists()) {
			Log.d("ddd", "file /proc/atmlqtouch/sleep/proto does not exists");
			return -1;
		}

		try {
			FileWriter Writer = new FileWriter(file);

			char[] buf = new char[8];
			Writer.write(state);
			//int state = reader.read();// can only write a char
			Writer.close();
			//state -= 0x30;//char to int
			//String tstr = new String(buf);
			return 0;
		} catch (IOException e) {
			Log.e("Serial", "error writing to WritePowerstate fs interface");
			e.printStackTrace();
		}
		return -1;

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	mManager = IdCardManager.getInstance();
		try {
			mManager.openDevice(this);
		} catch (IOException e) {
			// TODO: handle exception
			e.getMessage();
			tv.setText("错误：" + e.getMessage());
		}
		mManager.startRead(new IdCardManager.ReaderListener() {

			@Override
			public void onReadThing() {
				// TODO Auto-generated method stub
				point++;
				if (point > 14) {
					point = 0;
				}
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						tv.setText(getContinueStr());
					}
				});
			}

			@Override
			public void onRead(IDCard mIDCard) {
				// TODO Auto-generated method stub
				if (mIDCard != null && mIDCard.getIDCardNo() != null) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							JSONObject jsonObject = new JSONObject();
							try {
								jsonObject.put("name", mIDCard.getName().trim());

								jsonObject.put("id", mIDCard.getIDCardNo().trim());

								jsonObject.put("head", bitmaptoString(mIDCard.getHeadBitmap()));
							}catch (Exception e){
								e.printStackTrace();
							}
							MainActivity.ins.calljs(jsonObject);
							finish();
						}
					});


				}else {
					System.out.println(11);
				}

			}

			@Override
			public void onReadError(String error) {
				// TODO Auto-generated method stub
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						finish();
						startActivity(new Intent(IdCardReaderActivity.this,
								IdCardReaderActivity.class));
					}
				});
			}
		});
	}

	public String getContinueStr() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < point; i++) {
			sb.append(".");
		}
		return sb.toString();

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (mManager != null) {
			mManager.closeDevice();
		}
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	public String bitmaptoString(Bitmap bitmap) {
		// 将Bitmap转换成Base64字符串
		StringBuffer string = new StringBuffer();
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();

		try {
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
			bStream.flush();
			bStream.close();
			byte[] bytes = bStream.toByteArray();
			string.append(Base64.encodeToString(bytes, Base64.NO_WRAP));
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("string.."+string.length());
		return string.toString();
	}
}
